<template>
  <div>
    <vue-editor
      useCustomImageHandler
      @image-added="handleImageAdded"
      v-model="content"
    ></vue-editor>
  </div>
</template>

<script>
import FileApi from "@/api/file.js";
import { VueEditor } from "vue2-editor";
export default {
  components: {
    /*编辑器*/
    VueEditor,
  },
  name: "Editor",
  props: {
    /* 编辑器的内容 */
    value: {
      type: String,
      default: "",
    },
    /* 高度 */
    height: {
      type: Number,
      default: null,
    },
    /* 最小高度 */
    minHeight: {
      type: Number,
      default: null,
    },

    // 上传文件大小限制(MB)
    fileSize: {
      type: Number,
      default: 5,
    },
    /* 类型（base64格式、url格式） */
    type: {
      type: String,
      default: "url",
    },
  },
  data() {
    return {
      activeType: null,
      content:''
    };
  },
  computed: {
    styles() {
      let style = {};
      if (this.minHeight) {
        style.minHeight = `${this.minHeight}px`;
      }
      if (this.height) {
        style.height = `${this.height}px`;
      }
      return style;
    },
  },
  watch: {
    content(nval){
      this.$emit('change',nval);
    },
    value(nval){
      this.content = this.value;
    }
  },
  mounted() {
    this.content = this.value;
  },
  methods: {
    handleImageAdded(file, Editor, cursorLocation, resetUploader) {
      let self = this;
      const loading = this.$loading({
        lock: true,
        text: "图片上传中,请等待",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      const formData = new FormData();
      formData.append("iFile", file);
      formData.append("group_id", self.activeType);
      FileApi.uploadFile(formData)
        .then((res) => {
          console.log(res);
          loading.close();
          //在鼠标位置插入图片，保存的URL地址是this.editorUrl
          let url = res.data.file_path;
          Editor.insertEmbed(cursorLocation, "image", url);
          resetUploader();
          
        })
        .catch((err) => {
          loading.close();
          self.$message({
            message: "本次上传图片失败",
            type: "warning",
          });
        });
      
    },
    
  },
};
</script>

<style>
</style>
